//
//  WYJMainTabBar.swift
//  MySinaWeibo
//
//  Created by eastriver on 16/9/27.
//  Copyright © 2016年 believewilliam. All rights reserved.
//

import UIKit

class WYJMainTabBar: UITabBar {
    // 闭包属性
    var composeClosure: (() -> ())?
    // 懒加载属性
    private lazy var composeBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
        
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(self.composeBtn)
        // 添加点击事件
        composeBtn.addTarget(self, action: #selector(composeBtnDidClick), for: .touchUpInside)
    }
    
    @objc private func composeBtnDidClick() {
        composeClosure!()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
         super.layoutSubviews()
        var index = 0
        let btnWidth = self.bounds.width / 5
        let btnHeight = self.bounds.height
        
        for subV in subviews {
//            print(subV)
//            print("~~~~~~~~~~~~~~~~~~~~~~")
            // 判断是否是UITabBarButton
            if subV.isKind(of: NSClassFromString("UITabBarButton")!) {
                subV.frame = CGRect(x: CGFloat(index) * btnWidth, y: 0, width: btnWidth, height: btnHeight)
                index += (index == 1) ? 2 : 1
            }
        }
        composeBtn.frame.size =  CGSize(width: btnWidth, height: btnHeight)
        composeBtn.center = CGPoint(x: self.center.x, y: btnHeight * 0.5)
    }
}
